package com.tequila.core.service.impl;

import com.tequila.core.service.OAuthService;
import fe.core.Assert;
import fe.core.FastJson;
import fe.core.HttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * Created by fe on 2017/6/29.
 */
@Service
public class OAuthServiceImpl implements OAuthService {


    public static final Logger logger = LoggerFactory.getLogger(OAuthServiceImpl.class);

    public static final String WE_CHAT_GET_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token";
    public static final String WE_CHAT_APP_ID = "wx2ce9b87064d829d5";
    public static final String WE_CHAT_SECRET = "3661eb56e04171cbfb74b698be6cc295";
    public static final String WE_CHAT_GRANT_TYPE = "authorization_code";

    @Override
    public String getWechatAccessToken(String code) {
         Assert.assertNotNull(code,"第三方code不能为空!");

         StringBuffer url = new StringBuffer();
         url.append(WE_CHAT_GET_ACCESS_TOKEN).append("?");
         url.append("appid").append("=").append(WE_CHAT_APP_ID).append("&");
         url.append("secret").append("=").append(WE_CHAT_SECRET).append("&");
         url.append("grant_type").append("=").append(WE_CHAT_GRANT_TYPE);

         logger.info("wechat request url : {}",url);
         String result = HttpClientUtils.get(url.toString());
         logger.info("wechat response : {}",result);
         WeChatResult weChatResult = FastJson.fromJson(result,WeChatResult.class);
         return weChatResult.getAccess_token();
    }

    static class WeChatResult {
        private String access_token;
        private long expires_in;
        private String refresh_token;
        private String openid;
        private String scope;


        public String getAccess_token() {
            return access_token;
        }

        public void setAccess_token(String access_token) {
            this.access_token = access_token;
        }

        public long getExpires_in() {
            return expires_in;
        }

        public void setExpires_in(long expires_in) {
            this.expires_in = expires_in;
        }

        public String getRefresh_token() {
            return refresh_token;
        }

        public void setRefresh_token(String refresh_token) {
            this.refresh_token = refresh_token;
        }

        public String getOpenid() {
            return openid;
        }

        public void setOpenid(String openid) {
            this.openid = openid;
        }

        public String getScope() {
            return scope;
        }

        public void setScope(String scope) {
            this.scope = scope;
        }
    }
}
